﻿using System;
using System.Web.Mvc;
using NHibernate;
using NHibernate.Context;

namespace PCE.NH.AoP
{
	public class NHConversationFilter : IActionFilter
	{
		private readonly ISessionFactory _sessionFactory;

		public NHConversationFilter(ISessionFactory sessionFactory)
		{
			
			_sessionFactory = sessionFactory;
		}

		public void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var session = _sessionFactory.OpenSession();

			session.BeginTransaction();

			CurrentSessionContext.Bind(session);
		}

		public void OnActionExecuted(ActionExecutedContext filterContext)
		{
			var session = CurrentSessionContext.Unbind(_sessionFactory);

			var tx = session.Transaction;
			
			if (tx != null && tx.IsActive)
			{
				if (filterContext.Exception == null || filterContext.ExceptionHandled)
					tx.Commit();
				else
					tx.Rollback();
			}

			session.Close();
		}
	}
}